import { getToken, setToken, removeToken, setUserInfo } from '@/utils/auth'
import { constantRoutes } from '@/router/index'
import { resetRouter } from '@/router'
// import { GetOrderMaxCount } from '@/api/applicantInfoManagement/applicantInfoDetailList.js'
import { loginApi, rolePermission } from '@/api/login'
import { getUserInfo } from '@/utils/auth'
// import { Loading } from 'element-ui'
export default {
  // 开启命名空间
  namespaced: true,
  state () {
    return {
      token: getToken(),
      userInfo: {},
      routes: constantRoutes,
      roleId: null,
      role: null,
      btnList: [],
      isDynamicRouteAdded: false // 标记动态路由是否已加载
    }
  },
  mutations: {
    // 更新token
    updateToken (state, payload) {
      state.token = payload.token

      setToken(payload.token)
      setUserInfo(JSON.stringify(payload))
    },
    setUserInfoState (state, payload) {
      state.role = payload.data
    },
    // 删除token方法
    delToken (state, payload) {
      state.token = null
      state.roleId = null
      state.role = null

      removeToken()
      resetRouter()
    },
    updateRoutes (state, payload) {
      state.routes = [...constantRoutes, ...payload]
      // console.log(44,state.routes);
    },
    setRoleId (state, payload) {
      state.roleId = payload
    },
    updateBtnList (state, payload) {
      state.btnList = payload
    }
  },
  actions: {
    async storeLogin (context, payload) {
      const res = await loginApi(payload)
      context.commit('updateToken', res.data)
      context.commit('setRoleId', res.data.roleId)
    },
    async getUserInfo (context, payload) {
      // const loading = Loading.service({
      //   lock: true,
      //   text: '加载中',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(255,255, 255, 0.8)',
      //   fullscreen: true
      // })
      const result = await rolePermission({
        id: JSON.parse(getUserInfo()).roleId
      })
      // loading.close()
      context.commit('setUserInfoState', result)
      return result // 返回数据
    }
  }
}
